import DICTIONARY from './dictionary'

const obj = {
  ...DICTIONARY
}

/**
 *
 * @param {String} key 字典key
 * @return {Array<Object>}
 * @description 通过字典key 获得 options
 * @example
 * ```
 * let options =  makeOptions("SEX_TYPE")
 * ```
 */
const makeOptions = key => {
  if (
    !Object.prototype.hasOwnProperty.call(obj, key) &&
    process.env.NODE_ENV === 'development'
  ) {
    console.error(`警告:未能再字典中查询到${key}`)
  }
  const data = obj[key] || {}
  return data
}

/**
 * @param {String | Number} value 值
 * @param {String} key  字典key
 * @description 通过值获得对应的option
 * @example
 * ```
 * let color = valueToOption(2 , 'SEX_TYPE')
 * ```
 */
const valueToOption = (value, key) => {
  const options = makeOptions(key)
  let option = null
  if (Object.keys(options).length > 0) {
    option = options.find(option => {
      return option.value == value
    })
  }
  if (!option) {
    if (process.env.NODE_ENV === 'development') {
      console.error(`警告：未能再${key}中找到值为${value}的选项`)
    }
    return
  }
  return option
}
/**
 * @param {String | Number} value 值
 * @param {String} key  字典key
 * @return { String } defaultLabel 默认展示的文本
 * @description 通过值获得对应的label
 * @example
 * ```
 * let label = valueToLabel(2 , 'SEX_TYPE', '男')
 * ```
 */
const valueToLabel = (value, key, defaultLabel) => {
  const options = makeOptions(key)
  if (Object.keys(options).length > 0) {
    const option = options.find(option => {
      return option.value == value
    })
    if (!option) {
      if (process.env.NODE_ENV === 'development') {
        console.error(`警告：未能再${key}中找到值为${value}的选项`)
      }
      if (defaultLabel) return defaultLabel
    }
    return option?.label ? option.label : ''
  } else {
    if (defaultLabel) return defaultLabel
  }
}
export { makeOptions, valueToOption, valueToLabel }
export default Object.freeze(obj)
